﻿using Microsoft.AspNetCore.Http;
using Ocelot.LoadBalancer.LoadBalancers;
using Ocelot.Responses;
using Ocelot.Values;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MicroService.APIGateway
{
    public class CustomLoadBalancer : ILoadBalancer
    {
        private readonly Func<Task<List<Service>>> _services;
        private readonly object _lock = new object();

        private int _last;

        public CustomLoadBalancer(Func<Task<List<Service>>> services)
        {
            _services = services;
        }

        /// <summary>
        /// 利用tags标签配置自定义权重
        /// </summary>
        /// <param name="downstreamContext"></param>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public async Task<Response<ServiceHostAndPort>> Lease(HttpContext httpContext)
        {
            var services = await _services();
            lock (_lock)
            {
                List<Service> serviceList = new List<Service>();

                foreach(var service in services)
                {
                    int weight = int.Parse(service.Tags.ToArray()[0]);
                    for(int i = 0;i<weight;i++)
                        serviceList.Add(service);
                }
                
                var next = serviceList[_last++% serviceList.Count];
               
                return new OkResponse<ServiceHostAndPort>(next.HostAndPort);
            }
        }

       
        public void Release(ServiceHostAndPort hostAndPort)
        {
        }
    }
}
